<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="100px" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">销售单号：{{ form.saleOdd }}</div>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="4">
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="form.customerId" filterable placeholder="请选择">
              <el-option v-for="item in customerOptions" :key="item.customerId" :label="item.customerName" :value="item.customerId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售日期" prop="saleTime">
            <el-date-picker v-model="form.saleTime" clearable placeholder="请选择" type="date" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="出库仓库" prop="wareId">
            <treeselect v-model="form.wareId" :normalizer="normalizer" :options="wareOptions" placeholder="请选择" @select="handleTreeSelectNode"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售人" prop="salePersonId">
            <el-select v-model="form.salePersonId" filterable placeholder="请选择" @change="handleSelectedUser">
              <el-option v-for="item in personOptions" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="联系电话" prop="phonenumber">
            <el-input v-model="form.phonenumber" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button :disabled="!wareId" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAddCommodity">添加商品</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="form.detailsList" :summary-method="getSummaries" show-summary border>
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="商品编号" prop="commodityNo" width="150px;"/>
        <el-table-column align="center" label="商品名称" prop="commodityName1" width="200px;"/>
        <el-table-column align="center" label="商品类别" prop="commodityType" width="150px;"/>
        <el-table-column align="center" label="规格" prop="commoditySpec" width="150px;"/>
        <el-table-column align="center" label="单位" width="150px;">
          <template slot-scope="scope">
            <el-select v-model="scope.row.commodityUnitId" placeholder="请选择" @change="handleTableRowSelectChange($event, scope.row)">
              <el-option v-for="item in scope.row.unitList" :key="item.commodityUnitId" :label="item.unitName1" :value="item.commodityUnitId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位关系" prop="unitRelationship" width="150px;"/>
        <el-table-column align="center" label="换算结果" prop="unitResult" width="100px;"/>
        <el-table-column align="center" label="成本价" prop="costPrice"  width="100px;">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.costPrice) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="库存数量" prop="wareCommodityNumber" width="100px;"/>
        <el-table-column align="center" label="折扣率" prop="saleRate" width="200px;">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.saleRate" :max="1" :min="0.1" :step="0.1" size="mini" type="number"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="销售数量" prop="saleNumber" width="100px;">
          <template slot-scope="scope">
            <el-input v-model="scope.row.saleNumber" type="number" @input="calculateSubTotal(scope.row.saleNumber, scope.row, 'saleNumber')"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="销售单价" prop="salePrice" width="100px;">
          <template slot-scope="scope">
            <el-input v-model="scope.row.salePrice" type="number" @input="calculateSubTotal(scope.row.salePrice, scope.row, 'salePrice')"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计" prop="subtotal" width="100px;">
          <template slot-scope="scope">
            {{ formattedNumber(calculateSubTotal(scope.row.subtotal, scope.row, 'subtotal')) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="利润" prop="subtotalRate" width="100px;">
          <template slot-scope="scope">
            {{ formattedNumber(calculateSubTotal(scope.row.subtotalRate, scope.row, 'subtotalRate')) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="出库仓库ID" prop="outWareId" width="100px;" v-if="showDetailsColumn"/>
        <el-table-column align="center" label="出库仓库" prop="outWareName" width="100px;"/>
        <el-table-column align="center" label="备注" prop="detailsRemark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.detailsRemark" type="text"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="150px;">
          <template slot-scope="scope">
            <el-button v-hasPermi="['erp:ErpSupplierCommodity:remove']" icon="el-icon-delete" size="mini" type="text" @click="handleDeleteCommodity(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="15" style="margin-top: 40px">
        <el-col :span="6">
          <el-form-item label="物流费用" prop="logisticsCost">
            <el-input v-model="form.logisticsCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.logisticsMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="其他费用" prop="otherCost">
            <el-input v-model="form.otherCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.otherMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <div class="pay-amount-div">
        销售金额：<span style="margin-right: 40px;">{{ formattedNumber(form.payAmount) }}</span>
        销售利润：<span class="">{{ formattedNumber(form.rateMoney) }}</span>
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单据备注" prop="remark">
            <el-input v-model="form.remark" :rows="4" placeholder="请输入单据备注" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="附件" prop="attr">
          <file-upload v-model="form.attr"/>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm(1)">提交审核</el-button>
      <el-button type="primary" @click="submitForm(0)">保存草稿</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品" width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="wareId" @SelectionChange="handleSelectionChange"></ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getCustomerList} from '@/api/erp/ErpCustomer'
import {getSysUserList} from '@/api/system/user'
import {addErpSale, getErpSale, updateErpSale} from '@/api/erp/ErpSale'
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  components: {
    ErpCommodity,
    Treeselect
  },
  props: [],
  dicts: ['erp_procure_batch', 'erp_logistics_stauts'],
  data() {
    return {
      // 分摊方式
      methodOptions: [{
        value: 1,
        label: '按重量分摊'
      }, {
        value: 2,
        label: '按体积分摊'
      }],
      // 采购人列表
      personOptions: [],
      // 商品table loading
      loading: true,
      // 客户列表
      customerOptions: [],
      // 临时存放
      temporyList: [],
      // 选择商品弹框
      isCommodityOpen: false,
      // 仓库
      wareOptions: [],
      // 选中仓库id
      wareId: null,
      wareName: "",
      form: {},
      rules: {
        customerId: [
          {required: true, message: "请选择客户", trigger: "blur"}
        ],
        saleTime: [
          {required: true, message: "销售日期不能为空", trigger: "blur"}
        ],
        wareId: [
          {required: true, message: "请选择出库仓库", trigger: "blur"}
        ],
        salePersonId: [
          {required: true, message: "请选择销售人", trigger: "blur"}
        ],
      },
      // 过滤商品
      notCommodityIds: [],
      // 控制明系列是否显示
      showDetailsColumn:false,
    }
  },
  computed: {
    calculateSubtotal() {
      let subtotalSum = 0;
      this.form.detailsList.forEach(item => {
        subtotalSum += item.subtotal;
      })
      return parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) + parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) + subtotalSum;
    },
    calculateSubRateTotal() {
      let subtotalSum = 0;
      this.form.detailsList.forEach(item => {
        subtotalSum += item.subtotalRate;
      })
      return subtotalSum;
    }
  },
  watch: {
    'form.detailsList.subtotal': {
      handler(newVal) {
        this.form.payAmount = this.calculateSubtotal
        this.form.rateMoney = this.calculateSubRateTotal
      },
      deep: true
    },
    'form.logisticsCost': {
      handler(newVal) {
        this.form.payAmount = this.calculateSubtotal
        this.form.rateMoney = this.calculateSubRateTotal
      },
      deep: true
    },
    'form.otherCost': {
      handler(newVal) {
        this.form.payAmount = this.calculateSubtotal
        this.form.rateMoney = this.calculateSubRateTotal
      },
      deep: true
    },
  },
  created() {
    this.reset();
    this.handleGetListCustomer();
    this.handleGetListSysUser();
    this.getTreeselect();
    const saleId = this.$route.params && this.$route.params.saleId;
    if (saleId != 0) {
      this.getSaleInfo(saleId);
    } else {
      this.loading = false;
    }
  },
  mounted() {

  },
  methods: {
    formattedNumber,
    // 获取客户列表
    handleGetListCustomer() {
      getCustomerList().then(res => {
        this.customerOptions = res.data;
      })
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then(res => {
        this.personOptions = res.data;
      })
    },
    // 销售人人选择回调
    handleSelectedUser(e) {
      let obj = this.personOptions.find(i => {
        return i.userId == e
      })
      this.form.phonenumber = obj.phonenumber;
    },
    getSaleInfo(saleId) {
      getErpSale(saleId).then(response => {
        this.loading = false;
        this.form = response.data;
      });
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 表单重置
    reset() {
      this.form = {
        saleOdd: 'XS' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        customerId: null,
        saleTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
        salePersonId: null,
        logisticsCost: null,
        logisticsMethod: 1,
        otherCost: null,
        otherMethod: 1,
        payAmount: null,
        subtotal:0,
        rateMoney: 0,
        logisticsStauts: null,
        remark: null,
        attr: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        saleStatus: null,
        saleBatch: null,
        detailsList: []
      };
      this.resetForm("form");
    },
    // 商品单位选择
    handleTableRowSelectChange(e, row) {
      let obj = row.unitList.find(item => {
        return item.commodityUnitId == e
      })
      row.unitRelationship = obj.unitRelationship;
      row.unitResult = obj.unitResult;
      row.costPrice = obj.unitResult * obj.costPrice;
    },
    // 仓库选择
    handleTreeSelectNode(e) {
      this.wareId = e.wareId;
      this.wareName = e.wareName;
    },
    // 选择商品
    handleAddCommodity() {
      this.notCommodityIds = this.form.detailsList.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.detailsList.splice(index, 1);
      }
      this.notCommodityIds = this.notCommodityIds.filter(function (item) {
        return item !== row.commodityId;
      });
    },
    // 提交数据
    submitForm(type) {
      if(this.form.detailsList.length == 0){
        return this.$message.error('请选择销售商品！');;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.saleStatus = type;
          if (this.form.saleId != null) {
            updateErpSale(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/sale/ErpSale", name: "ErpSale"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpSale(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/sale/ErpSale", name: "ErpSale"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }

        }
      });
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/sale/ErpSale", name: "ErpSale"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach((item) => {
        this.form.detailsList.push({
          ...item,
          saleRate: 1,
          saleNumber: 1,
          salePrice: item.salePrice ? item.salePrice : item.retailPrice,
          outWareName:this.wareName,
          outWareId:this.wareId,
        });
      });
      this.isCommodityOpen = false;
    },
    /** 计算利润 */
    calculateProfitTotal(row) {
      row.profit = row.subtotal - (row.saleNumber * row.costPrice);
      return row.profit;
    },
    /** 计算小计 */
    calculateSubTotal(v, row, field) {
      if (v) {
        row[field] = v;
      }
      // 小计
      row.subtotal =
        parseFloat(!row.salePrice ? 0 : row.salePrice) *
        parseFloat(!row.saleNumber ? 0 : row.saleNumber) *
        parseFloat(!row.saleRate ? 1 : row.saleRate);
      // 利润
      row.subtotalRate = row.subtotal - (
        parseFloat(!row.costPrice ? 0 : row.costPrice) *
        parseFloat(!row.saleNumber ? 0 : row.saleNumber)
      )
      this.form.payAmount = 0;
      let subtotalSum = 0;
      let subtotalRateSum = 0;
      this.form.rateMoney = 0;
      this.form.detailsList.forEach((item) => {
        subtotalSum += item.subtotal;
        subtotalRateSum += item.subtotalRate;
      });
      this.form.payAmount =
        parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) +
        parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) +
        subtotalSum;
      this.form.rateMoney =  subtotalRateSum;
      return row[field];
    },
    checkNum(value) {
      let num = '' + value
      num = num
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace('.', '$#$')//把字符"."替换成'$#$',把'.'转换成一个比较特殊的字符防止被下一个正则替换给替换掉，因为replace对于字符串只匹配一次,所以只会替换第一个'.'
        .replace(/\./g, '')//把其余的字符'.'替换为空字符串(删除)
        .replace('$#$', '.')//把字符'$#$'替换回原来的'.'
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数。^字符串开始;第一组匹配,匹配1个'-';重复匹配`-`0-n个,但不进入分组 (\d+)第二组匹配,匹配1-n个数字; \.随后匹配一个'.'; (\d\d)第三组匹配,一个两位的数字; .*$后面匹配任意字符0-n个,直到字符串结束. 替换的目标是:'(第一组匹配)(第二组匹配).(第三组匹配)' */

      if (num.indexOf('.') < 0 && num !== '') {
        // 如果没有小数点，首位不能为类似于00、 01、02的数字
        num = parseFloat(num)
      }
      if (num >= 1) {
        // 当数字大于1时，改为1
        num = 1
      }
      value = num
      return value
    },
    /** 自定义合计 */
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (
          ["saleRate","saleNumber","salePrice","subtotal","subtotalRate"].includes(
            column.property
          )
        ) {
          if (index === 10) {
            sums[index] = "合计：";
          } else {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  let v = prev + curr;
                  return parseFloat(v.toFixed(4));
                } else {
                  return prev;
                }
              }, 0);
            } else {
              sums[index] = "0";
            }
          }
        }
      });
      return sums;
    },
  }
}

</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
